package com.duojuhe.common.utils.httputils;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * http请求
 *
 * @date 2018-05-30
 */
@Slf4j
public class HttpUtils {
    private static OkHttpClient tlClient;

    static {
        ConnectionPool tlPool = new ConnectionPool(50, 5, TimeUnit.MINUTES);
        tlClient = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .connectionPool(tlPool)
                .followRedirects(false)
                .retryOnConnectionFailure(true)
                .build();
    }


    /**
     * 同步方式去获取网络请求返回
     *
     * @param url
     * @param content
     * @return
     */
    public static String syncPost(String url, String content, String appKey, String sign) {
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), content);
        Request request = new Request.Builder()
                .method("POST", body)
                .url(url)
                .header("appKey", appKey)
                .header("sign", sign)
                .header("Connection", "close")
                .header("catch-control", "no-catch")
                .build();
        return httpResponse(url, request);
    }

    /**
     * 同步方式去获取网络请求返回
     *
     * @param url 请求地址
     */
    public static String syncGet(String url) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        return httpResponse(url, request);
    }

    /**
     * 判断客户端浏览器类型
     *
     * @param request
     * @return
     */
    public static String getBrowser(HttpServletRequest request) {
        String UserAgent = request.getHeader("User-Agent").toLowerCase();
        if (UserAgent.contains("firefox")) {
            return "FF";
        } else if (UserAgent.contains("safari")) {
            return "Chrome";
        } else {
            return "IE";
        }
    }


    /**
     * 调用接口返回
     */
    private static String httpResponse(String url, Request request) {
        Response response = null;
        ResponseBody responseBody = null;
        try {
            response = tlClient.newCall(request).execute();
            responseBody = response.body();
            if (response.isSuccessful()) {
                if (responseBody != null) {
                    return responseBody.string();
                }
                log.error("http responseBody null，requestUrl = {}",url);
            }
            log.error("http response error, code = {}，requestUrl = {}", response.code(),url);
        } catch (Exception e) {
            log.error("http request Exception, requestUrl = {}", url, e);
        } finally {
            if (responseBody != null) {
                responseBody.close();
            } else {
                if (response != null) {
                    response.close();
                }
            }
        }
        return null;
    }
}
